const _ = require('lodash');
const fs = require('fs');
var foodItemModel = require('../../app/models/foodItems.json');

module.exports = {
    getFoodItemByName: getFoodItemByName,
    getFoodItemByProducer: getFoodItemByProducer,
    findAllFoodItem: findAllFoodItem,
    addFoodItem: addFoodItem,
    deleteFoodItem: deleteFoodItem,
    getFoodItemByNameAndProducer: getFoodItemByNameAndProducer
}

function getFoodItemByName(name, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(name, item.name)) {
            result = item;
        }
    })
    callback(null, result);
}

function getFoodItemByProducer(producer, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(producer, item.producer)) {
            result = item;
        }
    })
    callback(null, result);
}

function getFoodItemByNameAndProducer(name, producer,callback){
    let result = null;
    let resList = new Array();
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(producer, item.producer) && _.isEqual(name, item.name)) {
            resList.push(item);
        }
    })
    callback(null, resList);
}

/// get all food
function findAllFoodItem(callback) {
    let result = null;
    let resList = new Array();
    _.forEach(foodItemModel, (item) => {
        resList.push(item);
    })
    callback(null, resList);
}

/// add foodItem
function addFoodItem(foodItem, callback) {
    if (foodItem == null) {
        callback("Error!", null);
    }
    foodItemModel.push(foodItem);
    ///append data to file
    fs.writeFile('./app/models/foodItems.json', JSON.stringify(foodItemModel,null,4), 'utf-8', (err) => {
        // fs.appendFile('./app/models/userInfo.json', JSON.stringify(userInfo),'utf-8', (err) => {
        if (err) throw err;
        callback(null, "success add foodItem");
    });
}

/// delete foodItem
function deleteFoodItem(id, callback) {
    if (id == null) {
        callback("Error!", null);
    }
    // let it = -1;
    // _.forEach(foodItemModel, (item,index) => {
    //     if(_.isEqual(id, item.itemId)) {
    //         it = index;
    //     }
    // });
    // if(!(_.isEqual(it, -1))){
    //     foodItemModel.splice(it,1);
    // }
    foodItemModel = _.filter(foodItemModel,(item)=>{
        return !(_.isEqual(id, item.itemId));
    });

    ///append data to file
    fs.writeFile('./app/models/foodItems.json', JSON.stringify(foodItemModel,null,4), 'utf-8', (err) => {
        // fs.appendFile('./app/models/userInfo.json', JSON.stringify(userInfo),'utf-8', (err) => {
        if (err) throw err;
        // callback(null, "success delete foodItem ,deleted index = "+ it);
        callback(null, "success delete foodItem");
    });
}